package com.peak.distribution.web.agent;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.peak.distribution.entity.agent.DisAgentSales;
import com.peak.distribution.entity.agent.DisAgentTeam;
import com.peak.distribution.exception.DistributionError;
import com.peak.distribution.exception.DistributionException;
import com.peak.distribution.manager.agent.DisAgentTeamManager;
import com.peak.distribution.service.agent.DisAgentService;
import com.peak.distribution.vo.agent.DisAgentSalesVo;
import com.peak.spring.boot.api.web.JsonMessage;
import com.peak.spring.boot.builder.repository.FilterParamBuilder;
import com.peak.spring.boot.builder.web.JsonBuilder;
import com.peak.spring.boot.core.web.BaseController;
import com.peak.spring.boot.tools.Emptys;

@RestController
@RequestMapping("/agent/sales")
public class DisAgentSalesController extends BaseController<DisAgentSales, DisAgentSalesVo> {
	
	@Autowired
	private DisAgentService disAgentService;
	
	@Autowired
	private DisAgentTeamManager agentTeamManager;

	@PostMapping("/current")
	public JsonMessage currentAgent(HttpServletRequest request) {
		// 当前登录代理商
		Integer agentId = disAgentService.getCurrentAgentId();
		if (Emptys.isEmpty(agentId)) {
			throw new DistributionException(DistributionError.AGENT_NOT_FOUND);
		}
		// 根据代理商找到销量表记录
		DisAgentSales sales = baseManager.findOne(FilterParamBuilder.create().eq("agent.id", agentId).build());
		if (Emptys.isEmpty(sales)) {
			throw new DistributionException(DistributionError.AGENT_SALES_NOT_FOUND);
		}
		return JsonBuilder.message().success().content(sales).convert(getVoClass()).build();
	}
	
	@PostMapping("/current/team")
	public JsonMessage currentTeam(HttpServletRequest request) {
		// 当前登录代理商
		Integer agentId = disAgentService.getCurrentAgentId();
		if (Emptys.isEmpty(agentId)) {
			throw new DistributionException(DistributionError.AGENT_NOT_FOUND);
		}
		// 找到他的团队
		DisAgentTeam team = agentTeamManager.findOne(FilterParamBuilder.create().eq("leader.id", agentId).build());
		if (Emptys.isEmpty(team)) {
			throw new DistributionException(DistributionError.AGENT_TEAM_NOT_FOUND);
		}
		// 根据团队找到销量表记录
		DisAgentSales sales = baseManager.findOne(FilterParamBuilder.create().eq("team.id", team.getId()).build());
		if (Emptys.isEmpty(sales)) {
			throw new DistributionException(DistributionError.AGENT_SALES_NOT_FOUND);
		}
		return JsonBuilder.message().success().content(sales).convert(getVoClass()).build();
	}
}
